//
//  LGTHttpUtil.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/9.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import Alamofire
import SAMKeychain
import WisdomHUD

class LGTHttpUtil: NSObject {
    
    static let httpUtil:LGTHttpUtil =  LGTHttpUtil()
    
    //超时时间待处理
    private let sharedSessionManager: Alamofire.SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        return Alamofire.SessionManager(configuration: configuration)
    }()
    
    public func uploadData(url:String, param:Dictionary<String, Any>, showMessage:Bool = false,success: @escaping ((Dictionary<String, Any>) -> Void), failure: @escaping ((Dictionary<String, Any>) -> Void)) -> Void{

        let imageData:Data = param["image"] as! Data
        let uploadURL:URL? = URL.init(string: url)
        if uploadURL == nil{
            return
        }
        
        //通用参数
        let requstParam = self.getParam(param: [:])
        let headers = ["content-type":"multipart/form-data"]
        let pstr = requstParam["_p"] as? String ?? ""
        self.sharedSessionManager.upload(multipartFormData: { (multipartFormData) in
            //多张图片上传
            multipartFormData.append(pstr.data(using: String.Encoding.utf8)!, withName: "_p")
            multipartFormData.append(imageData, withName: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
        }, to: url, headers: headers, encodingCompletion:{ encodingResult in
            switch encodingResult{
            case .success(request: let upload,_,_):
                upload.responseJSON(completionHandler: { (response) in
                    //数据处理
                    var successState:Bool = false
                    var json:[String:Any] = self.getJson(data: response.data ?? Data(), success: successState)
                    let state:Int = json["state"] as? Int ?? -1
                    
                    switch state{
                    //登陆信息过期
                    case 0:
                        successState = true
                        break
                    case 20000:
                        successState = false
                        break
                    //网络异常
                    case -1:
                        successState = false
                        break
                    default:
                        break
                    }
                    
                    if successState == true{
                        success(json)
                    }else{
                        failure(json)
                    }
                    
                    //登录信息处理
                    if state == 20000{
                        NotificationCenter.default.post(name: Offline_Note, object: nil)
                        return
                    }
                    
                    if showMessage == true{
                        let message:String = (json["message"] as? String) ?? ""
                        if state == 0{
                            WisdomHUD.showSuccess(text: message)
                        }else{
                            WisdomHUD.showError(text: message)
                        }
                    }
                    
                })
                break
            case .failure( _):
                failure( ["message":"网络错误",
                           "state": -1,
                            "data":[:]])
                break
            }
        })
    }
    
    public func requestData(url:String, param:Dictionary<String, Any>, showMessage:Bool = false,success: @escaping ((Dictionary<String, Any>) -> Void), failure: @escaping ((Dictionary<String, Any>) -> Void)) -> Void{
        
        //print(url)
        //请求参数封装处理
        let requstParam = self.getParam(param: param)
        self.sharedSessionManager.request(url, method: .post, parameters: requstParam, encoding: URLEncoding.default).responseJSON { (response) in
            //数据处理
            var successState:Bool = false
            var json:[String:Any] = self.getJson(data: response.data ?? Data(), success: successState)
            let state:Int = json["state"] as? Int ?? -1
            
            switch state{
                //登陆信息过期
            case 0:
                successState = true
                break
            case 20000:
                successState = false
                break
                //网络异常
            case -1:
                successState = false
                break
            default:
                break
            }

            
            if successState == true{
                success(json)
            }else{
                failure(json)
            }
            
            //登录信息处理
            if state == 20000{
                NotificationCenter.default.post(name: Offline_Note, object: nil)
                return
            }
            
            if showMessage == true{
                let message:String = (json["message"] as? String) ?? ""
                if state == 0{
                    WisdomHUD.showSuccess(text: message)
                }else{
                    WisdomHUD.showError(text: message)
                }
            }
        }
    }
    
    func getJson(data:Data, success:Bool) -> Dictionary<String, Any>{
        
//        let jsonAssci:String! = String(data: data, encoding: String.Encoding.nonLossyASCII)
//        let jsonStr2:String = AESCrypt.decrypt(jsonAssci, key: AppAesKey, iv: AppAesIV) ?? ""
        let dataStr:String = String(data: data, encoding: String.Encoding.utf8) ?? ""
        let jsonStr:String = AESCrypt.decrypt(dataStr, key: AppAesKey, iv: AppAesIV) ?? ""
        //print(jsonStr)
        var json:[String:Any] = [:]
        do{
            json = try JSONSerialization.jsonObject(with: jsonStr.data(using: String.Encoding.utf8) ?? Data(), options: .mutableContainers) as! [String:Any]
        }
        catch{
            json = ["message":"网络错误",
                    "state": -1,
                    "data":[:]]
        }
        return json
    }
    
    //参数封装
    func getParam(param:Dictionary<String, Any>) -> Dictionary<String, Any>{

//        var parameters:[String:Any] = param
//        parameters["client_code"] = APPUUID
//
//        let user_id = parameters["user_id"] as? Int ?? 0
//        if user_id == 0{
//            parameters["user_id"] = UserModel.share?.user_id ?? 0
//        }
//
//        let user_token:String = parameters["user_token"] as? String ?? ""
//        if user_token.count == 0{
//            parameters["user_token"] = UserModel.share?.user_token ?? ""
//        }
//        //用户类型
//        let user_Type:Int = parameters["user_type"] as? Int ?? -1
//        if user_Type == -1 && UserModel.share != nil{
//             parameters["user_type"] = UserModel.share?.user_type ?? 0
//        }
//
//        parameters["channel"] = KChannel
//        parameters["os"] = "2"
//        //parameters["type"] = 1
//        parameters["version"] = AppVersion
//        parameters["time"] = Int(Date.init().timeIntervalSince1970)
        
        var parameters:[String:Any] = BaseUtil.baseUtil.addCommonParam(param: param)
        //生成签名
        var sign:String = ""
        //排序
        let keys = parameters.keys
        var orderKeys = keys.sorted{(s1:String, s2:String) -> Bool in
            return s1 < s2
        }
        let count = orderKeys.count
        for index in 0..<count{
            let key:String = orderKeys[index]
            let value = String(describing: parameters[key]!)
            let s:String = "\(key)=\(value)&"
            sign.append(s)
        }
        sign.append("key=\(AppSignKey)")
        //sign md5加密
        let sign_md5:String = BaseUtil.baseUtil.md5(strs: sign)
        parameters["_s"] = sign_md5
        
        var p:String = ""
        do{
            let jsonData:Data = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
            let jsonUTF8:String! = String(data: jsonData, encoding: String.Encoding.utf8)
            p = AESCrypt.encrypt(jsonUTF8, key: AppAesKey, iv: AppAesIV)
        }
        catch{
        
        }
        let param:[String:Any] = ["_p": p]
        return param
    }
}

